var fs = require('fs');
var qr = require('qr-image');
var images = require("images");
var text2png = require('text2png');
var streamToPromise = require("stream-to-promise");
 
const text = process.argv[2];
const srcImage = process.argv[3];
const destImage = process.argv[4];

function generate_image() {
    const tempQrImage = "tmp_qr_img.png";
    const tempTextImage = "tmp_text_img.png";

    Promise.resolve()
    .then(() => {
        var qr_png = qr.image(text, { type: 'png',size : 5 , margin: 0});
        var qr_pipe = qr_png.pipe(fs.createWriteStream(tempQrImage));
        
        return streamToPromise(qr_pipe);
    })
    .then(() => {
        return new Promise((resolve, reject) => {
            fs.writeFileSync(tempTextImage, text2png(text, {color: 'red', font: '15px sans-serif'}));
            resolve();
        });
    })
    .then(() => {
        return new Promise((resolve, reject) => {
            images(srcImage)                    
                .draw(images(tempQrImage), 230, 460)
                .draw(images(tempTextImage), 240, 400)
                .save(destImage, {               
                    quality : 100               
                });
            resolve();
        })
    })
    .catch(e => {
        console.error(e);
    })
}

generate_image();